package com.xq.shop.controller.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xq.shop.po.Admin;
import com.xq.shop.service.admin.IAdminService;
import com.xq.shop.util.AdminServiceFactory;
import com.xq.shop.util.Const;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.util.RespUtil;
import com.xq.shop.vo.Operator;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.RespMsg.Result;

@Controller
public class LoginController {

	IAdminService adminService = AdminServiceFactory.getAdminService();
	
	/**
	 * 用户登录
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping("/admin/admin_login.do")
	public void login(String username, String password, HttpServletRequest request, HttpServletResponse response){
		
		Admin user = adminService.get(username, password);	//获取用户信息
		RespMsg msg = new RespMsg();	//设置返回信息
		
		/*在session中设置常用信息*/
		HttpSession session =  request.getSession();
		if(user != null){
			
			Operator operator = adminService.login(user);
			operator.setUser(user);
			session.setAttribute(Const.Operator_Session, operator);
			msg = new RespMsg(Result.success, "");	//设置成功返回信息
		} else {
			msg = new RespMsg(Result.error, "登录失败，用户名或密码错误!");
		}
		
		RespUtil.renderJson(GsonUtil.toJson(msg), response);
	}
	
	@RequestMapping("/admin/user_logout.do")
	public String logout(HttpServletRequest request, HttpServletResponse response){
		
		request.getSession().removeAttribute(Const.Operator_Session);
		return "admin/login";
	}
	
//	public ModelAndView adminIndex(HttpServletResponse response){
//		
//	}
}
